package com.easy.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.enumbean.RoleStatus;
import com.easy.common.service.IRoleService;
import com.easy.user.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Override
    public SysRole insert(SysRole role) {
        roleMapper.insert(role);
        SysRole result=this.getById(role.getId());
        return result;
    }

    @Override
    public SysRole update(SysRole role) {
        roleMapper.updateById(role);
        SysRole result=this.getById(role.getId());
        return result;
    }

    @Override
    public int delete(Integer id) {
        int num=roleMapper.deleteById(id);
        return num;
    }

    @Override
    public SysRole getById(Integer id) {
        SysRole result=roleMapper.selectById(id);
        return result;
    }

    @Override
    public IPage<SysRole> getListByPage(IPage page, SysRole role) {
        Wrapper wrapper=new QueryWrapper(role);
        IPage result=roleMapper.selectPage(page,wrapper);
        return result;
    }

    @Override
    public List<SysRole> getList(SysRole role) {
        Wrapper wrapper=new QueryWrapper(role);
        List<SysRole> result=roleMapper.selectList(wrapper);
        return result;
    }

    @Override
    public int setStatus(Integer id) {
        SysRole role=roleMapper.selectById(id);
        UpdateWrapper<SysRole> wrapper=new UpdateWrapper<>();
        if (role.getStatus()== RoleStatus.NORMAL){
            wrapper.set("status",RoleStatus.DISABLE);
        }else {
            wrapper.set("status",RoleStatus.NORMAL);
        }
        wrapper.set("id",role.getId());
        return roleMapper.update(wrapper);
    }

    @Override
    public SysRole assignPermission(SysRole role) {
        // 删除角色原有的权限关联
        roleMapper.deleteRolePermissionRelations(role.getId());

        // 插入新的权限关联
        List<Integer> permissionIds = role.getPermissionIds();
        if (permissionIds != null && !permissionIds.isEmpty()) {
            for (Integer permissionId : permissionIds) {
                roleMapper.insertRolePermissionRelation(role.getId(), permissionId);
            }
        }

        // 返回更新后的角色信息
        return this.getById(role.getId());
    }
    @Override
    public void getRolePermissions(SysRole role) {
        List<SysPermission> list=roleMapper.getPermissionsByRoleID(role.getId());
        role.setPermissions(list);
    }
}
